package com.westos.haohanbang.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class HaohanServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String id=request.getParameter("id");
        String name=request.getParameter("name");
        if(id==null) {
            InputStream in = request.getInputStream();
            String jsonstr = IOUtils.toString(in, "utf-8");
            JSONObject jsonobj = JSON.parseObject(jsonstr);
            id = jsonobj.getString("id");
            name = jsonobj.getString("name");
        }
        JSONObject json = new JSONObject();
        ServletContext application = getServletContext();
        Map haohans = (Map) application.getAttribute("haohans");
        if(haohans==null){
            haohans = new HashMap();
            id="1";
            name="哆啦A梦";
            haohans.put(id,name);
            application.setAttribute("haohans",haohans);
            json.put("msg","该英雄不存在,添加成功");
        }else{
            if(haohans.containsValue(name)){
                json.put("msg","该英雄已存在");
            }else{
                haohans.put(id,name);
                json.put("msg","该英雄不存在");
            }

        }
        json.put("haohans",haohans);
        response.getWriter().println(JSON.toJSONString(json, SerializerFeature.WriteSlashAsSpecial));
    }
}
